define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/stats/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        cst = require('js/frame/const'),
        app = Backbone.history;

    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var OrderListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch',
            'change #selectAll': 'selectAll',
            'change .check-row': 'checkRow',
            'click #export': 'exportData',
            'click #updateStatus': 'updateStatus',
            'click #switchSearchTime': 'changeSearchTime'
        },
        initialize: function (options) {
            this.options = options;
            this.collection = new models.OrderCollection();
            this.user_collection = new user_models.UserCollection();
            this.checkedIds = [];
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        exportData: function () {
            notify.warning('警告', '导出中，请等待');
            utils.exportData(this.collection.url, this._getSearchOption());
        },
        updateStatus: function () {
            var that = this;
            $.post('/admin/order/', JSON.stringify({
                ids: this.checkedIds,
                status: 2
            })).done(function (resp) {
                var data = resp.data;
                notify.success('提示', '更新成功！');
                that.doSearch();
            }).fail(function (data) {
                notify.notifyResp(data);
            });
        },
        selectAll: function (e) {
            var checked = $(e.target).is(':checked');
            $('.check-row').prop('checked', checked);
            if (!checked) {
                this.checkedIds = [];
            } else {
                this.checkedIds = this.collection.pluck('id');
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        checkRow: function (e) {
            var tr = $(e.target).closest('tr'),
                id = tr.data('id');
            if ($(e.target).is(':checked')) {
                this.checkedIds.push(id);
            } else {
                this.checkedIds = _.without(this.checkedIds, id);
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        _getSearchOption: function () {
            var options = {};
            var searched = utils.getAllInput('#sidebar_right');
            searched.status = parseInt($('#searchStatus').val());
            searched.user_id = parseInt($('#searchUserID').val());
            searched.activity_type = parseInt($('#searchActivityType').val());
            searched.bet_type = parseInt($('#searchBetType').val());
            searched.created_at_lower = $("#searchCreatedAtLower").val();
            searched.created_at_upper = $('#searchCreatedAtUpper').val();
            _.each(['status', 'activity_type', 'bet_type'], function (k) {
                if (searched[k] != -1) options[k] = searched[k];
            })
            if (!isNaN(searched.user_id)) {
                options.user_id = searched.user_id;
            }
            if (searched.id) {
                options.id = searched.id;
            }
            if (searched.created_at_lower || searched.created_at_upper) {
                options.created_at = {};
                if (searched.created_at_lower) options.created_at.$gte = searched.created_at_lower;
                if (searched.created_at_upper) options.created_at.$lt = searched.created_at_upper;
            }
            utils.saveSearched('op/order', searched);
            return options;
        },
        doSearch: function () {
            var options = this._getSearchOption();
            options.$page = 1;
            options.$size = 30;
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/order/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/order'),
                bet_list: window.get_bet_list(utils.getSearched('op/order').activity_type)
            }));
            var user_dict = {};
            _.each(this.user_collection.toJSON(), function (k) {
                user_dict[k.id] = k.nickname;
            });
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/order/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('[data-type=date]').datetimepicker({
                defaultDate: false,
                format: 'YYYY-MM-DD HH:mm:ss',
            });
            utils.getPaginator(that.options, this.collection.total, '#op/order/');

            return this;
        },
        load: function () {
            var that = this;
            this.user_collection.fetch({
                reset: true,
                data: {'disable_paginate': 1},
                success: function () {
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                        }
                    });
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                            $('#content').append('<h4 class="text-muted">无数据</h4>');
                        },
                    });
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                }
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "stats/OrderList.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 30;
            //if (!this.options.created_at) this.options.created_at = tz.today();
            var view = new OrderListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});
